package cc.sunni.admin.service.impl;

import cc.sunni.admin.mapper.AdminUserDao;
import cc.sunni.admin.service.AdminUserService;
import cc.sunni.api.utils.PageUtils;
import cc.sunni.api.utils.Query;
import cc.sunni.common.exception.RRException;
import cc.sunni.common.utils.ResultEnum;
import cc.sunni.pojo.AdminUser;
import cc.sunni.pojo.bo.NewAdminBO;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

@Service("adminUserService")
public class AdminUserServiceImpl extends ServiceImpl<AdminUserDao, AdminUser> implements AdminUserService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AdminUser> page = this.page(
                new Query<AdminUser>().getPage(params),
                // 拼接查询条件
                new LambdaQueryWrapper<AdminUser>()
        );

        return new PageUtils(page);
    }

    @Override
    public AdminUser queryAdminByUsername(String username) {
        return baseMapper.selectOne(new LambdaQueryWrapper<AdminUser>().eq(AdminUser::getUsername, username));
    }

    @Override
    @Transactional
    public void createAdminUser(NewAdminBO newAdminBO) {
        AdminUser adminUser = new AdminUser();
        adminUser.setUsername(newAdminBO.getUsername());
        adminUser.setAdminName(newAdminBO.getAdminName());

        // 如果密码不为空，则需要加密密码，存入数据库
        if (StringUtils.isNotBlank(newAdminBO.getPassword())) {
            String pwd = BCrypt.hashpw(newAdminBO.getPassword(), BCrypt.gensalt());
            adminUser.setPassword(pwd);
        }

        // 如果人脸上传以后，则有faceId，需要和admin信息关联存储入库
        if (StringUtils.isNotBlank(newAdminBO.getFaceId())) {
            adminUser.setFaceId(newAdminBO.getFaceId());
        }

        adminUser.setCreatedTime(new Date());
        adminUser.setUpdatedTime(new Date());

        int result = baseMapper.insert(adminUser);
        if (result != 1) {
            throw new RRException(ResultEnum.ADMIN_CREATE_ERROR);
        }
    }

}